using Dapper;
using Finance.Api.Read.Applications.Commands.调拨出入库记录;
using Finance.Api.Read.Dtos;
using Finance.ErrorCode;
using Finance.Infrastructure;
using MediatR;

namespace Finance.Api.Read.Applications.CommandHands.调拨出入库记录
{
    public class DeployOutRecordQueryCommandHandlers : IRequestHandler<DeployOutRecordQueryCommand, ApiResult<List<DeployOutRecordDto>>>
    {
        private readonly IDapperDb _db;
        private readonly ILogger<DeployOutRecordQueryCommandHandlers> _logger;

        public DeployOutRecordQueryCommandHandlers(IDapperDb db, ILogger<DeployOutRecordQueryCommandHandlers> logger)
        {
            _db = db;
            _logger = logger;
        }

        public async Task<ApiResult<List<DeployOutRecordDto>>> Handle(DeployOutRecordQueryCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<List<DeployOutRecordDto>>();

            try
            {
                var sql = @"
                    SELECT 
                        do.OutNo,
                        do.OutTime,
                        do.OutBox,
                        GROUP_CONCAT(dod.ProductName SEPARATOR ',') as ProductNames,
                        SUM(dod.OutNumNow) as TotalOutNum,
                        do.Outmessage
                    FROM DeployOut do
                    LEFT JOIN DeployOutDetail dod ON do.Id = dod.OutId
                    WHERE do.Deployment = @Deployment AND do.IsDelete = 0
                    GROUP BY do.Id, do.OutNo, do.OutTime, do.OutBox, do.Outmessage
                    ORDER BY do.OutTime DESC";

                var parameters = new DynamicParameters();
                parameters.Add("@Deployment", request.Deployment);

                var list = await _db.Query<DeployOutRecordDto>(sql, parameters);

                result.data = list.ToList();
                result.message = "调拨出库记录查询成功";
                result.Code = Enumcode.ok;
            }
            catch (Exception ex)
            {
                _logger.LogError("调拨出库记录查询失败: {Message}", ex.Message);
                result.message = "调拨出库记录查询失败";
                result.Code = Enumcode.fail;
                throw;
            }

            return await Task.FromResult(result);
        }
    }
} 